"use strict";

const { Compiler, RuntimeGlobals, RuntimeModule, runtime } = require("webpack");

/**
 * @extends {RuntimeModule}
 */
class InsertSnippetRuntimeModule extends RuntimeModule {
  constructor() {
    super("insertSnippet", RuntimeModule.STAGE_BASIC + 1);
  }

  /**
   * @returns {string}
   */
  generate() {
    return `
      const insertSnippet = window.insertSnippet;
      if (insertSnippet) {
        ${RuntimeGlobals.scriptNonce}.insertSnippet = insertSnippet;
      }
    `;
  }
}
/**
 * @typedef {import('webpack').WebpackPluginInstance} WebpackPluginInstance
 * @implements {WebpackPluginInstance}
 */
class InsertSnippetPlugin {
  /**
   * @readonly
   */
  static Name = "InsertSnippetPlugin";

  /**
   * @param {Compiler} compiler
   */
  apply(compiler) {
    compiler.options.devtool = false;
    compiler.hooks.thisCompilation.tap(
      InsertSnippetPlugin.Name,
      (compilation) => {
        compilation.hooks.additionalTreeRuntimeRequirements.tap(
          InsertSnippetPlugin.Name,
          (chunk, set) => {
            compilation.addRuntimeModule(
              chunk,
              new InsertSnippetRuntimeModule(),
            );
            return true;
          },
        );
      },
    );
  }
}

module.exports = { InsertSnippetPlugin };
